package my.framework.dubbo.sample.user.schedule;

import lombok.extern.slf4j.Slf4j;
import my.framework.dubbo.sample.model.user.UserDO;
import my.framework.dubbo.sample.service.user.UserService;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.annotation.Schedules;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author xuexue
 * @date 2018/11/20 22:55
 */
@Slf4j
@Component
public class RefreshUserCacheSchedule {
    @Resource
    private UserService userService;

    private String cacheGroup = "users";
    @Resource
    private RedisTemplate redisTemplate;


    @Schedules(
            {
                    /**
                     * 初始化后1s开始刷新1次,每半个小时刷新一次
                     */
                    @Scheduled(fixedRate = 1000 * 60 * 30, initialDelay = 1000),
                    /**
                     * 每10秒执行一次
                     */
                    @Scheduled(cron = "0/10 * * * * ?")
            }
    )
    public void refreshUserCache() {
        List<UserDO> users = userService.queryAll();
        users.forEach(u -> {
            redisTemplate.opsForValue().set(u.getId(), u);
        });
        log.info("refresh user[{}] cache success!", users.size());
    }
}
